package com.emmmya.ocs.config.autoRunner;

import com.emmmya.ocs.common.base.AbstractDefaultTask;
import com.emmmya.ocs.common.exception.CommonException;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @description: 任务执行器。会根据order排序后，依次执行
 * @author: 咕噜肉IT小店-黑医
 * @createDate: 2020-11-06
 * @version: 1.0
 */
@Data
@Slf4j
public class TaskRunner {

    private List<AbstractDefaultTask> tasks;

    public void run() throws Exception{
        if(tasks == null || tasks.isEmpty()){
            throw new CommonException("tasks不能为空！！可通过构造传入或通过setTasks设置。");
        }
        //先根据顺序排序
        sort(this.tasks);
        for(AbstractDefaultTask task: this.tasks) {
            task.run();
            //System.out.println("["+task.getTaskName()+"]:"+task.getMessage());
            log.info("["+task.getTaskName()+"]:"+task.getMessage());
        }
    }

    public TaskRunner(){
        super();
    }
    public TaskRunner(List<AbstractDefaultTask> tasks){
        this.tasks = tasks;
    }

    public static void sort(List<AbstractDefaultTask> tasks){
        Collections.sort(tasks, new Comparator<AbstractDefaultTask>() {
            @Override
            public int compare(AbstractDefaultTask o1, AbstractDefaultTask o2) {
                return o1.getOrder() - o2.getOrder();
            }
        });
    }

//    public static void main(String[] args) {
//        SelfCheckingFileManagementTask task1 = new SelfCheckingFileManagementTask();
//        SelfCheckingFileManagementTask task2 = new SelfCheckingFileManagementTask();
//        SelfCheckingFileManagementTask task3 = new SelfCheckingFileManagementTask();
//        SelfCheckingFileManagementTask task4 = new SelfCheckingFileManagementTask();
//
//        task1.setOrder(4);
//        task1.setTaskName("第4个自检任务");
//        task2.setOrder(3);
//        task2.setTaskName("第3个自检任务");
//        task3.setOrder(2);
//        task3.setTaskName("第2个自检任务");
//        task4.setOrder(1);
//        task4.setTaskName("第1个自检任务");
//        ArrayList<AbstractHarinDefaultTask> tasks = new ArrayList<>();
//        tasks.add(task1);
//        tasks.add(task2);
//        tasks.add(task3);
//        tasks.add(task4);
//        sort(tasks);
//        for(AbstractHarinDefaultTask task: tasks){
//            System.out.println(task.getTaskName()+"，"+task.getOrder());
//        }
//    }
}
